package com.xc.hotelmgr.datahandlermt.service.mt.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.hotelmgr.datahandlermt.pojo.mybatis.*;
import com.xc.hotelmgr.datahandlermt.pojo.request.BreakfastCal;
import com.xc.hotelmgr.datahandlermt.sdk.FxBaseApiRequest;
import com.xc.hotelmgr.datahandlermt.sdk.MtClient;
import com.xc.hotelmgr.datahandlermt.service.mt.CallBackService;
import com.xc.hotelmgr.datahandlermt.service.mybatis.*;
import com.xc.hotelmgr.datahandlermt.utils.ComUtil;
import com.xc.hotelmgr.datahandlermt.utils.MqType;
import com.xc.hotelmgr.datahandlermt.utils.RedisUtil;
import com.xc.hotelmgr.datahandlermt.utils.SendMessageMgr;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.sql.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CallBackServiceImpl implements CallBackService {

    private static final String GOODS_KEY = "1_rp_blong_htl_room";

    private final SendMessageMgr sendMessageMgr;

    private final RedisUtil redisUtil;

    /**
     * 房态回调
     * @param jsonObject
     */
    @Override
    public void rs(JSONObject jsonObject) {
        JSONObject callback = jsonObject.getJSONObject("data");
        JSONArray rsList = callback.getJSONArray("rsList");

        for (Object rs:rsList) {
            JSONObject jsonRS = (JSONObject) JSONObject.toJSON(rs);
            Long goodsId = jsonRS.getLong("goodsId");

            if(redisUtil.hashExistFiled(GOODS_KEY, goodsId.toString())) {
                List<HtDailyroom> htDailyrooms = new ArrayList<>();
                JSONArray goodsStatus = jsonRS.getJSONArray("goodsStatuses");
                for (Object goodsState : goodsStatus) {
                    JSONObject goodsStateJson = (JSONObject) JSONObject.toJSON(goodsState);
                    String strDate = goodsStateJson.getString("date");
                    Date date = (Date) ComUtil.dateStr2Date(strDate);
                    Long id = Long.parseLong(goodsId + ComUtil.dateStr2Integer(strDate));
                    HtDailyroom htDailyroom = new HtDailyroom();
                    Integer status = goodsStateJson.getInteger("status");
                    int num = 0;
                    if (status == 1) {
                        num = 3;
                    }
                    htDailyroom.setSaleNum(num);
                    htDailyroom.setRpCode(goodsId);
                    htDailyroom.setId(id);
                    htDailyroom.setPriceDate(date);
                    htDailyrooms.add(htDailyroom);
                }
                sendMessageMgr.sendMessage(MqType.CHANGERATES, htDailyrooms, "");
                log.info("s-goodsId: " + goodsId);
            }

        }
    }

    /**
     * rp回调
     * @param jsonObject
     */
    @Override
    public void rp(JSONObject jsonObject) {
        JSONObject callback = jsonObject.getJSONObject("data");
        List goodsList = callback.getJSONArray("goods");
        List<HtLogicRoom> htLogicRooms = new ArrayList<>();
        for (Object goods:goodsList) {
            JSONObject jsonRP = (JSONObject) JSONObject.toJSON(goods);
            HtLogicRoom htLogicRoom = new HtLogicRoom();
            Integer goodsType = jsonRP.getInteger("goodsType");
            String goodsId = jsonRP.getString("goodsId");          // 价格政策id
            // 价格
            List priceModels = jsonRP.getJSONArray("priceModels");
            if (goodsType != null && goodsType == 1) {
                if(redisUtil.hashExistFiled(GOODS_KEY, goodsId)) {
                    Long rpCode = jsonRP.getLong("goodsId");
                    Object cancelRules = jsonRP.getJSONArray("cancelRules"); // 取消规则list
                    Object bookRules = jsonRP.getJSONArray("bookRules");     // 预定规则list
                    Object breakfastList = jsonRP.get("breakfast"); // 早餐list
                    Object roomInfoList = jsonRP.get("roomInfoList"); //
                    if (cancelRules != null || bookRules != null || breakfastList != null || roomInfoList != null || priceModels == null) {
                        Long hotelCode = jsonRP.getLong("hotelId");
                        htLogicRoom.setHotelCode(hotelCode);  // set酒店编码

                        htLogicRoom.setRpCode(rpCode);   // set rp编码
                        String goodsName = jsonRP.getString("goodsName");
                        htLogicRoom.setRpName(goodsName);

                        if (roomInfoList != null) {
                            List roomList = (List) roomInfoList;
                            JSONObject roomInfo = (JSONObject) roomList.get(0);
                            Long roomCode = roomInfo.getLong("roomId");
                            htLogicRoom.setRoomCode(roomCode); // set房型编码
                        }

                        htLogicRoom.setId((long) Integer.parseInt(goodsId));

                        // 预定规则
                        if (bookRules != null) {
                            List bookRule = (List) bookRules;
                            JSONObject bookRuleJson = (JSONObject) bookRule.get(0);

                            // 连住天数（预定政策）
                            int serialCheckinMin = bookRuleJson.getInteger("serialCheckinMin");
                            int serialCheckinMax = bookRuleJson.getInteger("serialCheckinMax");
                            if (serialCheckinMin == 0) {
                                serialCheckinMin = 1;
                            }
                            if (serialCheckinMax == 0) {
                                serialCheckinMax = 90;
                            }

                            htLogicRoom.setMinDays(serialCheckinMin);
                            htLogicRoom.setMaxDays(serialCheckinMax);

                            // 最早预定时间数
                            int earlyNum = 30;// 初始设置最大时间30天
                            String earliestBookingDays = bookRuleJson.getString("earliestBookingDays");
                            if (earliestBookingDays != null & !"0".equals(earliestBookingDays) & !"-1".equals(earliestBookingDays)) {
                                earlyNum = Integer.parseInt(earliestBookingDays);
                            }
                            int earlyHours;
                            String earliestBookingHours = bookRuleJson.getString("earliestBookingHours");
                            int earlyAllHours;
                            if (earliestBookingHours != null) {
                                earlyHours = ComUtil.time2Hour(earliestBookingHours); // 凌晨向前的小时量
                                earlyAllHours = (earlyNum - 1) * 24 + earlyHours;
                            } else {
                                earlyAllHours = earlyNum * 24;
                            }
                            htLogicRoom.setMaxHours(earlyAllHours);

                            // 最晚预定时间数
                            int latestNum = 0;// 初始设置最小时间0天
                            String latestBookingDays = bookRuleJson.getString("latestBookingDays");
                            if (latestBookingDays != null & !"0".equals(latestBookingDays) & !"-1".equals(latestBookingDays)) {
                                latestNum = Integer.parseInt(latestBookingDays);
                            }
                            int latestHours;
                            String latestBookingHours = bookRuleJson.getString("latestBookingHours");
                            int latestAllHours;
                            int isDaybreakBooking = bookRuleJson.getInteger("isDaybreakBooking");
                            if (latestBookingHours != null) {
                                latestHours = ComUtil.time2Hour(latestBookingHours); // 凌晨向前的小时量
                                latestAllHours = latestNum * 24 + latestHours;
                            } else {
                                latestAllHours = latestNum * 24;
                            }
                            if (isDaybreakBooking == 1) {
                                latestAllHours = 0;
                            }
                            htLogicRoom.setMinHours(latestAllHours);
                        }

                        // 早餐规则
                        if (breakfastList != null) {
                            List bfList = (List) breakfastList;
                            for (Object breakfast : bfList) {
                                List<BreakfastCal> breakfastCals = new ArrayList<>(); // 某天的早餐规则
                                JSONObject breakfastJson = (JSONObject) JSONObject.toJSON(breakfast);

                                int breakfastNum = 0;
                                int breakfastType = breakfastJson.getInteger("breakfastType");
                                if (breakfastType == 1) {
                                    breakfastNum = breakfastJson.getInteger("breakfastNum");
                                }
                                int inStartDate = breakfastJson.getInteger("inStartDate");
                                int inEndDate = breakfastJson.getInteger("inEndDate");
                                if (inStartDate == 0 & inEndDate == 0) {
                                    htLogicRoom.setBreakfastNum(breakfastNum);
                                } else {
                                    BreakfastCal breakfastCal = new BreakfastCal();
                                    String startDate = ComUtil.intDate2String(inStartDate);
                                    String endDate = ComUtil.intDate2String(inEndDate);
                                    breakfastCal.setBreakfast_count(breakfastNum);
                                    breakfastCal.setDate(null);
                                    breakfastCal.setStartDate(startDate);
                                    breakfastCal.setEndDate(endDate);
                                    breakfastCals.add(breakfastCal);
                                }
                                if (!breakfastCals.isEmpty()) {
                                    htLogicRoom.setBreakfastCal(breakfastCals.toString());
                                }
                            }
                        }

                        // 取消规则
                        if (cancelRules != null) {
                            List calcelList = (List) cancelRules;
                            JSONObject cancel_policy = new JSONObject();
                            JSONObject cancelRuleJson = (JSONObject) calcelList.get(0);
                            int cancelType = cancelRuleJson.getInteger("cancelType");
                            if (cancelType == 0) {
                                cancel_policy.put("cancelPolicyType", 2);
                            } else {
                                cancel_policy.put("cancelPolicyType", 5);
                                JSONObject policyInfo = new JSONObject();
                                // 可取消
                                int aheadCancelDays = cancelRuleJson.getInteger("aheadCancelDays"); // 提前取消天数 0表示当天
                                int aheadHour = aheadCancelDays * 24; // 天数转换为小时
                                int allHour;  // 总时间量
                                int deductType = cancelRuleJson.getInteger("deductType");  // 提前取消类型
                                if (deductType == 0) {
                                    // 提前取消时间
                                    String aheadCancelHours = cancelRuleJson.getString("aheadCancelHours");
                                    int hour = ComUtil.time2Hour(aheadCancelHours);
                                    allHour = aheadHour + hour;  // 总时间
                                    if (allHour <= 0) {
                                        allHour = 1;
                                    }
                                    policyInfo.put("timeBefore", allHour);
                                } else {
                                    // 提前取消时间量
                                    int aheadCancelHours = cancelRuleJson.getInteger("aheadCancelHours");
                                    allHour = aheadHour + aheadCancelHours; // 总时间
                                    if (allHour <= 0) {
                                        allHour = 1;
                                    }
                                    policyInfo.put("timeBefore", allHour);
                                }
                                cancel_policy.put("policyInfo", policyInfo);
                            }
                            htLogicRoom.setCancelPolicy(cancel_policy.toJSONString());
                        }

                        // 价格计划状态
                        int status = 1;
                        if (jsonRP.getInteger("goodsStatus") != 1) {
                            status = 2;
                        }
                        htLogicRoom.setStatus(status);

                        // 价格计划放入list
                        htLogicRooms.add(htLogicRoom);
                    }

                    List<HtDailyroom> htDailyrooms = new ArrayList<>();
                    assert priceModels != null;
                    for (Object priceModel : priceModels) {
                        JSONObject jsonPriceModel = (JSONObject) JSONObject.toJSON(priceModel);
                        String strDate = jsonPriceModel.getString("date");
                        Date date = (Date) ComUtil.dateStr2Date(strDate);
                        Long id = Long.parseLong((goodsId + ComUtil.dateStr2Integer(strDate)));
                        int price = jsonPriceModel.getInteger("salePrice");
                        HtDailyroom htDailyroom = new HtDailyroom();

                        htDailyroom.setRpCode(rpCode);
                        htDailyroom.setPriceDate(date);
                        htDailyroom.setPrice(price);
                        htDailyroom.setId(id);
                        htDailyrooms.add(htDailyroom);
                    }
                    if (!htDailyrooms.isEmpty()) {
                        sendMessageMgr.sendMessage(MqType.CHANGERATES, htDailyrooms, "");
                        log.info("p-goodsId: " + goodsId);
                    }
                }
            }
        }
        if(!htLogicRooms.isEmpty()) {
            sendMessageMgr.sendMessage(MqType.CHANGERP, htLogicRooms, "");
        }
    }


    /**
     * 酒店信息回调
     * @param jsonObject
     */
    @Override
    public void poi(JSONObject jsonObject) {

            JSONObject callback = jsonObject.getJSONObject("data");
            List hotelList = callback.getJSONArray("hotelList");

            for (Object hotel:hotelList) {
                JSONObject jsonHotel = (JSONObject) JSONObject.toJSON(hotel);
                Long hotelCode = jsonHotel.getLong("hotelId");
                HtHotelinfo htHotelinfo = new HtHotelinfo();
                htHotelinfo.setId(hotelCode);
                sendMessageMgr.sendMessage(MqType.CHANGEHOTEL, htHotelinfo, "");
            }

    }
}
